package com.itheima.exam.service.impl;


import com.itheima.exam.constant.AppConstant;
import com.itheima.exam.exception.UserException;
import com.itheima.exam.mapper.UserMapper;
import com.itheima.exam.pojo.entity.User;
import com.itheima.exam.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public User login(User user) {
        //根据用户名去数据库查询用户
        User loginUser = userMapper.findUserByUsername(user.getUsername());

        //1.判断用户是否为null
        if(loginUser == null){
            //说明不存在该用户
            throw new UserException(AppConstant.LOGIN_USER_NOT_EXIST);
        }

        //2.用户名密码校验
        String password = user.getPassword();
        //对用户传递的密码进行md5 数字摘要算法
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!loginUser.getPassword().equals(password)) {
            //说明用户名密码错误
            throw new UserException(AppConstant.LOGIN_PASSWORD_ERR);
        }

        //3.用户状态校验
        if(loginUser.getStatus() == 0){
            //用户被禁用
            throw new UserException(AppConstant.LOGIN_USER_DISABLE);
        }

        return loginUser;
    }
}
